<template>
  <div class="appointments-container">
    <h2 style="text-align: center;">我的预约</h2>

    <!-- 搜索陪诊员 -->
    <div class="search-box">
      <div class="search-input-wrapper">
        <el-input v-model="searchKeyword" placeholder="输入陪诊员ID进行搜索" class="short-input" />
        <el-button type="primary" @click="searchEscorts">搜索</el-button>
      </div>
    </div>

    <!-- 新增预约表单 -->
    <div class="new-appointment-form" v-if="showNewAppointmentForm">
      <h3 style="text-align: center;">新增预约</h3>
      <el-form :model="newAppointment" label-width="120px">
        <el-form-item label="陪诊员ID">
          <el-input v-model="newAppointment.escortId" disabled />
        </el-form-item>
        <el-form-item label="陪诊员姓名">
          <el-input v-model="newAppointment.escortName" disabled />
        </el-form-item>
        <el-form-item label="服务类型" required>
          <el-select v-model="newAppointment.serviceTypeId" placeholder="请选择服务类型">
            <el-option
                v-for="service in serviceTypes"
                :key="service.id"
                :label="service.name"
                :value="service.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="预约时间" required>
          <el-date-picker
              v-model="newAppointment.appointmentTime"
              type="datetime"
              placeholder="选择预约时间"
              value-format="YYYY-MM-DD HH:mm:ss"
          />
        </el-form-item>
        <el-form-item label="服务时长(小时)">
          <el-input-number v-model="newAppointment.duration" :min="1" :max="8" />
        </el-form-item>
        <el-form-item label="联系人姓名" required>
          <el-input v-model="newAppointment.contactName" />
        </el-form-item>
        <el-form-item label="联系电话" required>
          <el-input v-model="newAppointment.contactPhone" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitAppointment">提交预约</el-button>
          <el-button @click="cancelNewAppointment">取消</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 搜索结果 -->
    <div v-if="searching" class="search-result">
      <p>正在搜索...</p>
    </div>

    <!-- 搜索结果 -->
    <div v-else-if="searchResults.length > 0" class="search-result">
      <h4 style="text-align: center;">搜索到的陪诊员：</h4>
      <div class="escort-list">
        <div v-for="escort in searchResults" :key="escort.id" class="escort-card">
          <p><strong>ID:</strong> {{ escort.id }}</p>
          <p><strong>姓名:</strong> {{ escort.realName }}</p>
          <p><strong>手机号:</strong> {{ escort.phone }}</p>
          <p><strong>性别:</strong> {{ escort.gender }}</p>
          <p><strong>年龄:</strong> {{ escort.age }}</p>
          <p><strong>服务次数:</strong> {{ escort.serviceCount }}</p>
          <p><strong>平均评分:</strong> {{ escort.avgRating }}</p>
          <el-button
              type="primary"
              size="small"
              @click="prepareNewAppointment(escort)"
          >
            预约此陪诊员
          </el-button>
        </div>
      </div>
    </div>

    <div v-else-if="searchKeyword && !searchResults.length" class="search-result">
      <p>未找到相关陪诊员</p>
    </div>

    <!-- 预约统计 -->
    <div class="appointment-count">
      当前共有 {{ appointments.length }} 个预约
    </div>

    <!-- 筛选选项 -->
    <div class="filter-options">
      <label for="statusFilter">状态筛选：</label>
      <el-select v-model="statusFilter" id="statusFilter" @change="fetchAppointments">
        <el-option label="全部" value="all" />
        <el-option label="待确认" value="pending" />
        <el-option label="已确认" value="confirmed" />
        <el-option label="已完成" value="completed" />
        <el-option label="已取消" value="cancelled" />
      </el-select>
    </div>

    <!-- 预约列表 -->
    <el-table :data="appointments" style="width: 100%" border>
      <el-table-column prop="id" label="预约ID" width="100" />
      <el-table-column prop="escortName" label="陪诊员" />
      <el-table-column label="预约时间" width="220">
        <template #default="{row}">
          {{ formatDateTime(row.appointmentTime) }}<br>
          ({{ calculateDuration(row.appointmentTime, row.endTime) }}小时)
        </template>
      </el-table-column>
      <el-table-column prop="contactName" label="联系人" />
      <el-table-column prop="contactPhone" label="联系电话" />
      <el-table-column prop="status" label="状态" width="120">
        <template #default="{row}">
          <el-tag :type="getStatusTagType(row.status)">
            {{ getStatusText(row.status) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="paymentStatus" label="支付状态" width="120">
        <template #default="{row}">
          <el-tag :type="getPaymentTagType(row.paymentStatus)">
            {{ getPaymentText(row.paymentStatus) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="totalAmount" label="总金额" width="120">
        <template #default="{row}">
          ¥{{ row.totalAmount }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="220">
        <template #default="scope">
          <el-button size="small" @click="viewDetails(scope.row)">详情</el-button>
          <el-button
              size="small"
              type="danger"
              @click="cancelAppointment(scope.row)"
              :disabled="scope.row.status !== 'pending'"
          >
            取消
          </el-button>
          <el-button
              size="small"
              type="success"
              @click="payAppointment(scope.row)"
              :disabled="scope.row.paymentStatus !== 'unpaid'"
          >
            支付
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
        layout="prev, pager, next"
        :total="total"
        v-model:current-page="currentPage"
        :page-size="pageSize"
        @current-change="fetchAppointments"
        style="margin-top: 20px"
    />

    <!-- 预约详情对话框 -->
    <el-dialog v-model="detailDialogVisible" title="预约详情" width="50%">
      <div v-if="currentAppointment">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="预约ID">{{ currentAppointment.id }}</el-descriptions-item>
          <el-descriptions-item label="陪诊员">{{ currentAppointment.escortName }}</el-descriptions-item>
          <el-descriptions-item label="预约时间">
            {{ formatDateTime(currentAppointment.appointmentTime) }} - {{ formatTime(currentAppointment.endTime) }}
          </el-descriptions-item>
          <el-descriptions-item label="联系人">{{ currentAppointment.contactName }}</el-descriptions-item>
          <el-descriptions-item label="联系电话">{{ currentAppointment.contactPhone }}</el-descriptions-item>
          <el-descriptions-item label="状态">
            <el-tag :type="getStatusTagType(currentAppointment.status)">
              {{ getStatusText(currentAppointment.status) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="支付状态">
            <el-tag :type="getPaymentTagType(currentAppointment.paymentStatus)">
              {{ getPaymentText(currentAppointment.paymentStatus) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="总金额">¥{{ currentAppointment.totalAmount }}</el-descriptions-item>
          <el-descriptions-item label="创建时间">{{ formatDateTime(currentAppointment.createTime) }}</el-descriptions-item>
        </el-descriptions>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button
              v-if="currentAppointment && currentAppointment.status === 'completed'"
              type="primary"
              @click="showReviewDialog"
          >
            评价服务
          </el-button>
          <el-button
              v-if="currentAppointment"
              type="success"
              @click="toggleFavorite(currentAppointment.escortId)"
          >
            {{ isFavorite(currentAppointment.escortId) ? '已收藏' : '收藏陪诊员' }}
          </el-button>
          <el-button @click="detailDialogVisible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import axios from 'axios'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRouter } from 'vue-router'

const BASE_URL = 'http://localhost:8080'
const router = useRouter()

// 数据模型
const appointments = ref([])
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const statusFilter = ref('all')

const searchKeyword = ref('')
const searching = ref(false)
const searchResults = ref([])
const favorites = ref([])

const serviceTypes = ref([
  { id: 1, name: '普通陪诊' },
  { id: 2, name: '检查陪诊' },
  { id: 3, name: '儿童陪诊' },
  { id: 4, name: '长者陪诊' },
  { id: 5, name: '急诊陪诊' },
  { id: 6, name: '术后陪诊' }
])

const showNewAppointmentForm = ref(false)
const newAppointment = ref({
  escortId: '',
  escortName: '',
  serviceTypeId: '1', // 新增服务类型ID
  appointmentTime: '',
  duration: 2,
  contactName: '',
  contactPhone: ''
})

const detailDialogVisible = ref(false)
const currentAppointment = ref(null)

// 日期时间格式化
const formatDateTime = (date) => {
  if (!date) return ''
  const d = new Date(date)
  return `${d.getFullYear()}-${padZero(d.getMonth() + 1)}-${padZero(d.getDate())} ${padZero(d.getHours())}:${padZero(d.getMinutes())}`
}

const formatTime = (date) => {
  if (!date) return ''
  const d = new Date(date)
  return `${padZero(d.getHours())}:${padZero(d.getMinutes())}`
}

const padZero = (num) => {
  return num < 10 ? `0${num}` : num
}

const calculateDuration = (start, end) => {
  if (!start || !end) return 0
  const startTime = new Date(start).getTime()
  const endTime = new Date(end).getTime()
  return ((endTime - startTime) / (1000 * 60 * 60)).toFixed(1)
}

// 获取预约列表
const fetchAppointments = async () => {
  try {
    const params = {
      page: currentPage.value,
      size: pageSize.value,
      status: statusFilter.value === 'all' ? null : statusFilter.value
    }

    const res = await axios.get(BASE_URL + '/v1/user/appointments', { params })
    if (res.data.state === 2000) {
      appointments.value = res.data.data || []
      total.value = res.data.total || 0
    } else {
      ElMessage.error(res.data.msg)
    }
  } catch (error) {
    console.error('获取预约失败:', error)
    ElMessage.error('获取预约列表失败')
  }
}

// 获取收藏列表
const fetchFavorites = async () => {
  try {
    const res = await axios.get(BASE_URL + '/v1/user/favorites/list')
    if (res.data.state === 2000) {
      favorites.value = res.data.data || []
    }
  } catch (error) {
    console.error('获取收藏列表失败:', error)
  }
}

// 搜索陪诊员
const searchEscorts = async () => {
  if (!searchKeyword.value.trim()) {
    searchResults.value = []
    return
  }

  searching.value = true
  try {
    const params = {
      keyword: searchKeyword.value,
      page: 1,
      size: 5
    }

    const res = await axios.get(BASE_URL + '/v1/user/favorites/search-escort', { params })
    if (res.data.state === 2000) {
      searchResults.value = res.data.data || []
    } else {
      ElMessage.error(res.data.msg)
    }
  } catch (error) {
    console.error('搜索陪诊员失败:', error)
    ElMessage.error('搜索陪诊员失败')
  } finally {
    searching.value = false
  }
}

// 准备新增预约
const prepareNewAppointment = (escort) => {
  newAppointment.value = {
    escortId: escort.id,
    escortName: escort.realName,
    serviceTypeId: 1, // 默认选择第一个服务类型
    appointmentTime: '',
    duration: 2,
    contactName: '',
    contactPhone: ''
  }
  showNewAppointmentForm.value = true
}

// 提交预约
const submitAppointment = async () => {
  try {
    // 验证必填字段
    if (!newAppointment.value.contactName || !newAppointment.value.contactPhone) {
      ElMessage.warning('请填写联系人信息')
      return
    }

    if (!newAppointment.value.appointmentTime) {
      ElMessage.warning('请选择预约时间')
      return
    }

    if (!newAppointment.value.serviceTypeId) {
      ElMessage.warning('请选择服务类型')
      return
    }

    // 从localStorage获取用户信息
    const userInfo = JSON.parse(localStorage.getItem('user'))
    if (!userInfo || !userInfo.id) {
      ElMessage.warning('用户未登录或登录已过期')
      return
    }

    // 计算结束时间
    const startTime = new Date(newAppointment.value.appointmentTime)
    const endTime = new Date(startTime.getTime() + newAppointment.value.duration * 60 * 60 * 1000)

    // 构建预约数据
    const appointmentData = {
      userId: userInfo.id, // 添加用户ID
      escortId: newAppointment.value.escortId,
      serviceTypeId: Number(newAppointment.value.serviceTypeId),
      appointmentTime: formatToBackendDateTime(newAppointment.value.appointmentTime),
      endTime: formatToBackendDateTime(endTime),
      contactName: newAppointment.value.contactName,
      contactPhone: newAppointment.value.contactPhone,
      status: "pending",
      paymentStatus: "unpaid",
      totalAmount: calculateTotalAmount(newAppointment.value.serviceTypeId, newAppointment.value.duration)
    }

    console.log('提交的预约数据:', appointmentData)

    const res = await axios.post(BASE_URL + '/v1/user/appointments/book', appointmentData, {
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${localStorage.getItem('token')}` // 添加认证token
      }
    })

    if (res.data && res.data.state === 2000) {
      ElMessage.success('预约提交成功')
      showNewAppointmentForm.value = false
      fetchAppointments()
    } else {
      ElMessage.error(res.data?.msg || '预约提交失败')
    }
  } catch (error) {
    console.error('提交预约失败:', error)
    ElMessage.error(error.response?.data?.message || '提交预约失败')
  }
}

// 根据服务类型和时长计算总金额
const calculateTotalAmount = (serviceTypeId, duration) => {
  // 这里可以根据不同的服务类型设置不同的单价
  const pricePerHour = {
    1: 100, // 普通陪诊
    2: 150, // 检查陪诊
    3: 120, // 儿童陪诊
    4: 130, // 长者陪诊
    5: 200, // 急诊陪诊
    6: 180  // 术后陪诊
  }
  return duration * (pricePerHour[serviceTypeId] || 100)
}

// 专门为后端格式化的方法
const formatToBackendDateTime = (date) => {
  if (!date) return ''
  const d = new Date(date)
  return `${d.getFullYear()}-${padZero(d.getMonth() + 1)}-${padZero(d.getDate())} ${padZero(d.getHours())}:${padZero(d.getMinutes())}:${padZero(d.getSeconds())}`
}

// 取消新增预约
const cancelNewAppointment = () => {
  showNewAppointmentForm.value = false
}

// 查看详情
const viewDetails = (appointment) => {
  currentAppointment.value = appointment
  detailDialogVisible.value = true
}

// 取消预约
const cancelAppointment = async (appointment) => {
  try {
    await ElMessageBox.confirm('确定要取消此预约吗?', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    const res = await axios.put(BASE_URL + `/v1/user/appointments/${appointment.id}/cancel`)
    if (res.data.state === 2000) {
      ElMessage.success('取消预约成功')
      fetchAppointments()
    } else {
      ElMessage.error(res.data.msg)
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('取消预约出错:', error)
      ElMessage.error(error.response?.data?.message || '取消预约失败')
    }
  }
}

// 跳转到评价页面
const showReviewDialog = () => {
  router.push({
    path: '/user/reviews',
    query: {
      appointmentId: currentAppointment.value.id,
      escortId: currentAppointment.value.escortId
    }
  })
}

// 切换收藏状态
const toggleFavorite = async (escortId) => {
  try {
    if (isFavorite(escortId)) {
      await axios.delete(`${BASE_URL}/v1/user/favorites/cancel/${escortId}`)
      ElMessage.success('已取消收藏')
    } else {
      await axios.post(`${BASE_URL}/v1/user/favorites/add`, { escortId })
      ElMessage.success('收藏成功')
    }
    fetchFavorites()
  } catch (error) {
    console.error('操作收藏失败:', error)
    ElMessage.error(error.response?.data?.message || '操作失败')
  }
}

// 检查是否已收藏
const isFavorite = (escortId) => {
  return favorites.value.some(f => f.escortId === escortId)
}

// 支付预约
const payAppointment = async (appointment) => {
  try {
    await ElMessageBox.confirm('确定要支付此预约吗?', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    const res = await axios.put(BASE_URL + `/v1/user/appointments/${appointment.id}/pay`)
    if (res.data.state === 2000) {
      ElMessage.success('支付成功')
      fetchAppointments()
    } else {
      ElMessage.error(res.data.msg)
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('支付出错:', error)
      ElMessage.error(error.response?.data?.message || '支付失败')
    }
  }
}

// 状态标签类型
const getStatusTagType = (status) => {
  switch (status) {
    case 'pending': return 'warning'
    case 'confirmed': return 'primary'
    case 'completed': return 'success'
    case 'cancelled': return 'danger'
    default: return 'info'
  }
}

// 状态文本
const getStatusText = (status) => {
  switch (status) {
    case 'pending': return '待确认'
    case 'confirmed': return '已确认'
    case 'completed': return '已完成'
    case 'cancelled': return '已取消'
    default: return status
  }
}

// 支付状态标签类型
const getPaymentTagType = (status) => {
  switch (status) {
    case 'paid': return 'success'
    case 'unpaid': return 'danger'
    case 'refunded': return 'info'
    default: return 'info'
  }
}

// 支付状态文本
const getPaymentText = (status) => {
  switch (status) {
    case 'paid': return '已支付'
    case 'unpaid': return '未支付'
    case 'refunded': return '已退款'
    default: return status
  }
}

onMounted(() => {
  fetchAppointments()
  fetchFavorites()
})
</script>

<style scoped>
/* 主容器背景和字体颜色 */
.appointments-container {
  padding: 30px;
  background-color: #f0f8ff;
  color: #2e2e2e;
  font-family: 'Segoe UI', sans-serif;
}

/* 搜索区域阴影增强 */
.search-box .search-input-wrapper {
  box-shadow: 0 2px 10px rgba(70, 130, 180, 0.2);
  border-radius: 10px;
  padding: 10px;
  background: white;
}

/* 输入框圆角优化 */
.short-input :deep(.el-input__inner) {
  border-radius: 8px;
  border: 1px solid #cce0ff;
}

/* 搜索按钮渐变色 */
.el-button--primary {
  background: linear-gradient(to right, #4a90e2, #6bc1ff);
  border: none;
  transition: background 0.3s ease;
}

.el-button--primary:hover {
  background: linear-gradient(to right, #6bc1ff, #3a90e2);
}

/* 预约统计文字美化 */
.appointment-count {
  font-size: 1.1rem;
  margin-bottom: 15px;
  font-weight: bold;
  color: #1e3d59;
  text-align: center;
  letter-spacing: 1px;
}

/* 筛选下拉选择框美化 */
.filter-options label {
  font-weight: bold;
  color: #6bbaff;
  margin-right: 10px;
}

.filter-options .el-select {
  width: 150px;
}

/* 卡片式陪诊员信息展示 */
.escort-card {
  background-color: white;
  border-radius: 12px;
  box-shadow: 0 4px 15px rgba(70, 130, 180, 0.15);
  padding: 20px;
  min-width: 220px;
  transition: transform 0.2s ease, box-shadow 0.3s ease;
  border: 1px solid #d0e0ff;
}

.escort-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 6px 20px rgba(70, 130, 180, 0.3);
}

/* 分页样式微调 */
.el-pagination {
  display: flex;
  justify-content: center;
  margin-top: 25px;
}

/* 其他已有样式保持不变... */
.search-box {
  margin-bottom: 20px;
  display: flex;
  justify-content: center;
}

.search-input-wrapper {
  display: flex;
  align-items: center;
  gap: 10px;
}

.short-input {
  width: 200px;
}

.escort-list {
  display: flex;
  flex-wrap: wrap;
  justify-content: center;
  gap: 20px;
  padding: 0 10px;
}

/* 新增预约表单样式 */
.new-appointment-form {
  background-color: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  margin-bottom: 20px;
}
</style>